﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;

namespace TVGrid
{
    class AutoSizePanel : Grid
    {
        public AutoSizePanel()
        {
            this.SizeChanged += new SizeChangedEventHandler(CostumeWrapPanelSizeChanged);
        }

        //when a child is added or removed
        protected override void OnChildDesiredSizeChanged(UIElement child)
        {
            PrintChilders();
            base.OnChildDesiredSizeChanged(child);
        } 

        //when window size change
        void CostumeWrapPanelSizeChanged(object sender, SizeChangedEventArgs e)
        {
            PrintChilders();
        }

        //creates rows and columns in the grid accurding to the 
        //number of childrens and arrange the childrens in the grid
        private void PrintChilders()
        {
            
            int chiledcount = this.Children.Count;
            UIElementCollection childrens = this.Children;
            //double WandH;
            bool breakFlag = false;
            this.RowDefinitions.Clear();
            this.ColumnDefinitions.Clear();
            for (int i = 1; i < 5; i++)
            {
                if (chiledcount <= Math.Pow(i, i))
                {
                    for (int x = 0; x < i; x++)
                    {
                        this.RowDefinitions.Add(new RowDefinition());
                        this.ColumnDefinitions.Add(new ColumnDefinition());
                    }
                    break;
                }
            }

            int counter = 0;
            for (int x = 0; x < this.RowDefinitions.Count; x++)
            {
                for (int i = 0; i < this.ColumnDefinitions.Count; i++)
                {
                    if (!(counter >= childrens.Count))
                    {
                        Grid.SetColumn(childrens[counter], i);
                        Grid.SetRow(childrens[counter], x);

                        (childrens[counter]).SetValue(WidthProperty, ActualWidth / this.ColumnDefinitions.Count);
                        counter++;
                    }
                    else
                    {
                        breakFlag = true;
                        break;
                    }
                }
                if (breakFlag)
                    break;
            }
        }
    }
}
